package com.jjt.kiki.other;
import java.util.BitSet;

/** 
 * 
 * @author jiangjt 
 */  
public class BloomFilter {
	
	//单例模式设计
	private static class Single{
		private static final BloomFilter f = new BloomFilter();
	}
	
	private BloomFilter() {
		
	}
	
	public static BloomFilter getInstance() {
		return Single.f;
	}
	
	//一个小型的hash算法
	private static class MySimpleHash {
		//容器大小
	    private int myCap;  
	    //种子数
	    private int mySeed;
	    
	    private  MySimpleHash(int myCap, int mySeed) {  
	        this.myCap = myCap;  
	        this.mySeed = mySeed;  
	    }  
	  
	    private int myHash(String value) {//字符串哈希，选取好的哈希函数很重要  
	        int result = 0;  
	        int len = value.length();  
	        for (int i = 0; i < len; i++) {  
	            result = mySeed * result + value.charAt(i);  
	        }  
	        return (myCap - 1) & result;  
	    }  
	}  
    private static final int MY_BLOOM_SIZE = 2 << 24;  
    private static final int[] BLOOM_SEED = {3,5,7, 11, 13, 31, 37, 61};
    private static final BitSet bits = new BitSet(MY_BLOOM_SIZE);  
    private static final MySimpleHash[] func = new MySimpleHash[BLOOM_SEED.length];  
  
    {
    	 for (int i = 0; i < BLOOM_SEED.length; i++) {  
             func[i] = new MySimpleHash(MY_BLOOM_SIZE, BLOOM_SEED[i]);  
         }  
    }
      
    public  void add(String value){  
        if(value != null) {
        	  synchronized (this) {
        		  for(MySimpleHash f : func)
                      bits.set(f.myHash(value),true);  
			}
        }	  
     }  
      
    public  boolean contains(String value){  
        if(value == null) return false;  
        boolean ret = true;  
        synchronized (this) {
        	 for(MySimpleHash f : func) {  
                 ret = ret && bits.get(f.myHash(value));  
                 if(ret==false)
                 	return ret;
             }
             return ret;  
		}
    }  
    
    public static void main(String[] args) {
    	System.out.println(2<<24);
    }
}  
  
